using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml.Automation.Peers;
using Microsoft.UI;
using Windows.Graphics;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Threading.Tasks;
using CheckNetIsolation.CheckNetIsolationInit;
using System.Reflection.Metadata.Ecma335;



namespace CheckNetIsolation
{
    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        public  MainWindow()  
        {
            this.InitializeComponent();
            ExtendsContentIntoTitleBar = true;
            SetTitleBar(AppTitleBar);
			  initListViewAsync(); 
			changeWindowsSize();
			


		}

       private   void    changeWindowsSize()
		{ 
			IntPtr hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this); // 获取窗口句柄 
			var windowId = Win32Interop.GetWindowIdFromWindow(hwnd); // 获取窗口ID 
			AppWindow appWindow = AppWindow.GetFromWindowId(windowId); 
			appWindow.Resize(new SizeInt32(600, 800 )); // 设置窗口大小 
			 
		}

		public async Task initListViewAsync()
		{

			 UWPAPPS apps  = new UWPAPPS();  
			  List<Item>  allUWPAppInfo =  await apps.getAllUWPAppInfoAsync();
          originalItems = new ObservableCollection<Item>(allUWPAppInfo);
			UWPAPPListView.ItemsSource = originalItems  ;  

		}
		   
	 
		private ObservableCollection<Item>? originalItems =new ObservableCollection   <Item>();
		  
		private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			if (originalItems == null)
			{
				return;
			}

			var searchText = SearchTextBox.Text.ToLower().Trim() ;
			var filteredItems = originalItems.Where(item => (bool)(item.AppName?.ToLower().Trim().Contains(searchText, StringComparison.CurrentCultureIgnoreCase))).ToList();
			UWPAPPListView.ItemsSource = filteredItems;
		}

		private void SelectAllCheckBox_Checked(object sender, RoutedEventArgs  e)
		{  
			if (originalItems == null) return; 
			foreach (var item in originalItems)
			{
				item.AppIsChecked = true;
			}
			
		}

		private void SelectAllCheckBox_Unchecked(object sender, RoutedEventArgs e)
		{ 
			if (originalItems == null) return; 
			foreach (var item in originalItems)
			{
				item.AppIsChecked = false;
			}
		}
		private   void StartExemptForApps(object sender, RoutedEventArgs e) { 
			if (originalItems == null) return;
			// CheckNetIsolation loopbackexempt -a -n=<应用的包名称>  
			try
			{ 
				 List <Item> allSelectedItems =     []  ;
				// 获取选中的项 
				allSelectedItems = originalItems.Where(item => item.AppIsChecked).ToList();
				if (allSelectedItems.Count == 0) return;
				 List <string>  appid =  ExactAppID(allSelectedItems);
				 
				foreach (var item in appid)
				{   
				  // 调用 CheckNetIsolation loopbackexempt -a  -p=appid 
					string command = $"loopbackexempt -a  -n={item}"; 
					System.Diagnostics.Process.Start("CheckNetIsolation", command); 

				}

				 
			} 
			catch (Exception ex)
			{
				// 处理异常，例如：显示日志或消息框
				System.Diagnostics.Debug.WriteLine($"发生错误: {ex.Message}");
			}
		}
		private List <string> ExactAppID(List<Item> allSelectedItems)
		{

			// 使用 FindAll 方法找出所有 ID 不等于 "1" 的项
			return new List<string>(allSelectedItems.Where(item => item.ID != "1") .Select(item => item.ID)).ToList();
		}
		public void CancelExemptForApps(object sender, RoutedEventArgs e) {

			if (originalItems == null) return;
			// CheckNetIsolation loopbackexempt -d  -n=<应用的包名称>  
			try
			{
				List<Item> allSelectedItems = null;
				// 获取选中的项 
				allSelectedItems = originalItems.Where(item => item.AppIsChecked).ToList();
				if (allSelectedItems.Count == 0) return;
				foreach (var item in allSelectedItems)
				{
					string command = $"loopbackexempt -d  -n={item.AppName}";
					System.Diagnostics.Process.Start("CheckNetIsolation", command);
				}


			}
			catch (Exception ex)
			{
				// 处理异常，例如：显示日志或消息框
				System.Diagnostics.Debug.WriteLine($"发生错误: {ex.Message}");
			}
		}
		private async Task  showDialog( )
		{
			// 创建一个新的 ContentDialog
			var dialog = new ContentDialog
			{
				Title = "模态框标题",  
				Content = "这是一个模态框的内容。",
				CloseButtonText = "关闭"
			};

			// 显示模态框并等待用户操作
			await dialog.ShowAsync();
		}
		private void ResetButton_Click(object sender, RoutedEventArgs e)
		{
			if (originalItems == null) return;
			SearchTextBox.Text = string.Empty;
			SelectAllCheckBox.IsChecked = false; 
			 var   result  = new List<Item>(originalItems);
			foreach (var item in originalItems)
			{
				//var temp = item;

				item.AppIsChecked = false;
				//temp.AppIsChecked = false; 
				//result .Add(temp ); 
			}
			UWPAPPListView.ItemsSource = null; // 清空数据源 
			UWPAPPListView.ItemsSource = originalItems ; // 还原数据源 
		}
		///  ------  <summary>
		private void Item_ItemCheckedChanged(object sender, EventArgs e)
		{
			if (sender is Item item) // 确保 sender 是 Item 类型
			{
				UpdateSelectAllCheckBox(); // 根据 item 状态更新全选复选框
			}
		}

		/// </summary>
		private void UpdateSelectAllCheckBox()
		{
			if (originalItems == null || originalItems.Count == 0)
			{
				SelectAllCheckBox.IsChecked = false;
				return;
			}

			// 检查是否所有项都被选中
			bool allChecked = originalItems.All(item => item.AppIsChecked);
			SelectAllCheckBox.IsChecked = allChecked;

			// 检查是否有选中项
			bool anyChecked = originalItems.Any(item => item.AppIsChecked);
			SelectAllCheckBox.IsThreeState = true;
			SelectAllCheckBox.IsChecked = allChecked ? true : anyChecked ? (bool?)null : false;
		}



	}
	public class Item  : INotifyPropertyChanged  
	{
		public string  ?  ID { get; set; }  
		public   string  ?AppName { get; set; }
		public     string  ?   AppPath { get; set; }  
		private   bool  _appIsChecked; 
		public   bool   AppIsChecked { get => _appIsChecked ; set { 
					_appIsChecked = value;
					OnPropertyChanged(nameof(AppIsChecked));


					ItemCheckedChanged?.Invoke(this, EventArgs.Empty); // 触发事件
			}}
		public  event   EventHandler    ItemCheckedChanged; 
		public event PropertyChangedEventHandler ? PropertyChanged; // event 是 关键字   后面接委托 
		protected virtual void OnPropertyChanged(string propertyName)
		{
			 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
		}

	}; 


}
